/*
 * @Description: request.js
 * @Author: zhangchenna
 * @Date: 2019-02-19 14:23:18
 * @LastEditTime: 2019-02-21 17:46:11
 */
export default class http {
    static fetch(options) {
        let engine = null,
            params = formsParams(options.data);

        engine = new XMLHttpRequest();

        options = options || {};
        options.success =
            options.success ||
            function() {
                // eslint-disable-line
            };
        options.fail =
            options.fail ||
            function() {
                // eslint-disable-line
            };

        if (options.type == 'get' || options.type == 'GET') {
            engine.open(options.type, options.url + '?' + params, options.async);
            engine.send(null);
        } else if (options.type == 'post' || options.type == 'POST') {
            engine.open(options.type, options.url, options.async);
            engine.setRequestHeader(
                'Content-Type',
                'application/x-www-form-urlencoded; charset=UTF-8'
            );
            engine.send(params);
        }

        engine.onreadystatechange = function() {
            if (engine.readyState == 4) {
                let status = engine.status;
                if ((status >= 200 && status < 300) || status === 304) {
                    options.success(engine.response);
                } else {
                    options.fail(engine.onerror);
                }
            }
        };

        function formsParams(data) {
            let arr = [];
            for (let prop in data) {
                arr.push(prop + '=' + data[prop]);
            }
            return arr.join('&');
        }
    }
}
